package ar.edu.itba.pod.legajo48240.utils;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import ar.edu.itba.balance.api.AgentsBalancer;
import ar.edu.itba.balance.api.AgentsTransfer;
import ar.edu.itba.event.RemoteEventDispatcher;
import ar.edu.itba.node.Node;
import ar.edu.itba.node.NodeInformation;
import ar.edu.itba.node.api.ClusterAdministration;
import ar.edu.itba.node.api.StatisticReports;
import ar.edu.itba.pod.legajo48240.model.Host;

public class Net {

	public static ClusterAdministration getCluster(String host, int port) throws RemoteException, NotBoundException{
		Registry registry = LocateRegistry.getRegistry(host, port);
		try{
			registry.lookup(Node.CLUSTER_COMUNICATION);
		}catch (Exception e) {
			e.printStackTrace();
			//TODO;
		}
		
		return  (ClusterAdministration) registry.lookup(Node.CLUSTER_COMUNICATION);
		
	}
	
	public static RemoteEventDispatcher getDispatcher(String host, int port) throws RemoteException, NotBoundException{
		Registry registry = LocateRegistry.getRegistry(host, port);
		return  (RemoteEventDispatcher) registry.lookup(Node.DISTRIBUTED_EVENT_DISPATCHER);
	}
	
	public static AgentsBalancer getBalancer(NodeInformation node) throws RemoteException, NotBoundException{
		Registry registry = LocateRegistry.getRegistry(node.host(), node.port());
		return  (AgentsBalancer) registry.lookup(Node.AGENTS_BALANCER);
	}
	
	public static AgentsTransfer getTransferer(NodeInformation node) throws RemoteException, NotBoundException{
		Registry registry = LocateRegistry.getRegistry(node.host(), node.port());
		return  (AgentsTransfer) registry.lookup(Node.AGENTS_TRANSFER);
	}

	public static StatisticReports getStatistic(NodeInformation node) throws RemoteException, NotBoundException{
		Registry registry = LocateRegistry.getRegistry(node.host(), node.port());
		return  (StatisticReports) registry.lookup(Node.STATISTIC_REPORTS);
	}
	
	public static void disconnectFromGroup(Host localhost, NodeInformation node) {
			try {
				localhost.network().disconnectFromGroup(node);
			} catch (Exception ignore) {} // starts as local method 
	}
}
